/*
 * @Descripttion: 
 * @version: 1.0.0
 * @Author: wangjinyan
 * @Date: 2020-07-23 20:05:52
 * @LastEditors: wangjinyan
 * @LastEditTime: 2022-11-03 11:02:36
 */ 
import {assetManager, Asset } from "cc";
type _types_globals__Constructor<T = unknown> = new (...args: any[]) => T;
type Constructor<T = unknown> = _types_globals__Constructor<T>;
type AssetType<T = Asset> = Constructor<T>;

export default class Tools {
	static loadJson(file, func):void {
		assetManager.loadAny(file, (err, object) => {
			if (err) {
				func(null);

				return;
			}

			if (func) {
				func(object.json);
			}
		});
	}

	static ranInt(min, max):number {
		return Math.round(Math.random() * (max - min) + min);
	}

	static ranFloat(min,max):number{
		return Math.random() * (max - min) + min;
	}

	static async delayTime(time:number):Promise<void>{
		return new Promise<void>(resolve=>{
			setInterval(()=>{
				resolve();
			},time*1000)
		})
	}

	/**
	 * @description 
	 * 	let testStr = "测试啊啊{0}xxx {1} {2}"
    	let str = Tools.stringFormat(testStr,'我啊',111,"eeee")
        console.log("str:",str)
		console.log("testStr:",testStr)
		//  str: 测试啊啊我啊xxx 111 eeee
		//  testStr: 测试啊啊{0}xxx {1} {2}
	 * @param str 
	 * @param args 
	 */
	static stringFormat(str:string,...args:any[]):string{
		const len = args.length;

		for (let i = 0; i < len; i++) {
			const value = args[i];
			const key = `{${i}}`;

			str = str.replace(key,value.toString());
		}

		return str
	}

	/**
	 * 格式化%s类型的字符串
	 * @param str 
	 * @param args 
	 * @returns 
	 */
	static stringFormat2(str:string,...args:any[]):string{
		const array = str.split('%s');
		let result = ''

		for (let i = 0; i < array.length; i++) {
			result += array[i];
			if (i < args.length) {
				result += args[i];
			}
			
			// const value = args[i];
			// let index = str.indexOf('%s');
			// if (index!=-1) {
			// 	let key = `{${i}}`;
			// 	str = str.replace(key,value.toString());
			// }
		}

		return result
	}
	// public static stringFormat3(str:string, ...args:any[]){
	// 	var result = str;
	// 		for (var i = 0; i < args.length; i++) {
	// 			if (args[i] != undefined) {
	// 				var reg= new RegExp("({)" + i + "(})", "g");
	// 				result = result.replace(reg, args[i]);
	// 				// console.log("----------result----------",i,objs[i]);
	// 			}
	// 		}
	// 	return result;
	// }
	
	/*
		时间格式转换
	*/
	public static timerFormat1(tparm):string {
		// console.log("timerFormat:",time);
		const time = Math.round(tparm);
		const t = Number(time);
		const m = Math.floor(t / 60);
		const s = t % 60;
		const strM = m < 10 ? '0' + m : m;
		const strS = s < 10 ? '0' + s : s;
		const str = `${strM}:${strS}`;

		// console.log("timerFormat:",str);
		return str;
	}


	public static timerFormat(tparm):string {
		// console.log("timerFormat:",time);
		const time = Math.round(tparm);
		const t = Number(time);
		const h = Math.floor(t / 3600);
		const m = Math.floor((t - h * 3600) / 60);
		const s = t % 60;
		const strH = h < 10 ? '0' + h : h;
		const strM = m < 10 ? '0' + m : m;
		const strS = s < 10 ? '0' + s : s;

		if (h != 0) {
			const str = `${strH}:${strM}:${strS}`;

			return str;
		}
		else{
			const str = `${strM}:${strS}`;

			return str;
		}
	}

	public static timerFormatZH1(tparm):string {
		// console.log("timerFormat:",time);
		const time = Math.round(tparm);
		const t = Number(time);
		const d = Math.floor(t / 3600/24);
		const h = Math.floor(t%(3600*24)/ 3600);
		const m = Math.floor((t%(3600*24) - h * 3600) / 60);
		const s = t % 60;

		// let str_h = h < 10 ? '0' + h : h;
		// let str_m = m < 10 ? '0' + m : m;
		// let str_s = s < 10 ? '0' + s : s;
		if (d != 0) {
			const str = `${d}天${h}时${m}分`;

			return str;
		}
		else if (h != 0) {
			const str = `${h}小时${m}分${s}秒`;

			return str;
		}
		else{
			const str = `${m}分钟${s}秒`;

			return str;
		}
	}

	public static timerFormatZH(tparm):string {
		// console.log("timerFormat:",time);
		const time = Math.round(tparm);
		const t = Number(time);
		const h = Math.floor(t / 3600);
		const m = Math.floor((t - h * 3600) / 60);
		const s = t % 60;
		const strH = h < 10 ? '0' + h : h;
		const strM = m < 10 ? '0' + m : m;
		const strS = s < 10 ? '0' + s : s;

		if (h != 0) {
			const str = `${strH}小时${strM}分${strS}秒`;

			return str;
		}
		else{
			const str = `${strM}分${strS}秒`;

			return str;
		}
	}

	public static nameFormat(name: string):string {
		let temName = '';
		let bytesCount = 0;

		if (this.getBytesCount(name) <= 5) {
			return name;
		}

		for (let i = 0; i < name.length; i++) {
			const c = name.charAt(i);

			if (/^[\u0000-\u00ff]$/.test(c)) // 匹配双字节
			{
				bytesCount += 1;
			}
			else {
				bytesCount += 2;
			}

			if (bytesCount <= 8) {
				temName += name[i];
			}
			else {
				temName += '...';
				break;
			}
		}

		return temName;
	}

	public static getBytesCount(str):number {
		if (str === null) {
			return 0;
		}
		else {
			return (str.length + str.replace(/[\u0000-\u00ff]/g, '').length);
		}
	}

	public static nameFormat1(nameP):string {
		let name = nameP;

		if (!name) {
			return name;
		}

		if (name.length > 5) {
			name = name.substr(0, 5) + '..';
		}

		return name;
	}

	// 金额单位转换
	public static getMoney(money):string {
		let lbmoney = '0';

		if (money >= 1000000000000) {
			lbmoney = `${(money / 1000000000000).toFixed(2)}t`;
		}
		else if (money >= 1000000000) {
			lbmoney = `${(money / 1000000000).toFixed(2)}b`;
		} else if (money >= 1000000) {
			lbmoney = `${(money / 1000000).toFixed(2)}m`;
		}
		else if (money >= 10000) {
			lbmoney = `${(money / 1000).toFixed(2)}k`;
		}
		else if (money >= 1000) {
			lbmoney = `${(money / 1000).toFixed(2)}k`;
		}
		else {
			lbmoney = `${(money).toFixed(0)}`;
		}

		return lbmoney;
	}

	public static strFormat(str:string, objs):string{
		let result = str;

		for (let i = 0; i < objs.length; i++) {
			if (objs[i] != undefined) {
				const reg= new RegExp("({)" + i + "(})", "g");

				result = result.replace(reg, objs[i]);
				// console.log("----------result----------",i,objs[i]);
			}
		}

		return result;
	}

	private static _unitsEn = ["K", "M", "B", "T", 
		"aa", "ab" ,"ac","ad","ae","af","ag",'ah','ai','aj','ak','al','am','an',"ao", "ap" ,"aq","ar","as","at","au",'av','aw','ax','ay','az',
		"ba", "bb" ,"bc","bd","be","bf","bg",'bh','bi','bj','bk','bl','bm','bn',"bo", "bp" ,"bq","br","bs","bt","bu",'bv','bw','bx','by','bz'
	];

	public static longNumberFormat(num:number):string{
		if (num < 10000)
			return `${Math.floor(num)}`
		else
		{
			let i = 0;
			const mod = 1000;

			while (num >= mod){
				num = num / mod;
				i = i + 1;
			}

			if(i > 0)
			{
				const num1 :number = Math.floor(num);
				const num2 :number = Math.floor(((num - num1) * 10));

				if(num2 >= 1)
				{
					return `${num1}.${num2}${this._unitsEn[i - 1]}`
				}
				else
					return `${num1}${this._unitsEn[i - 1]}`
			}
		}
	}

	public static randomWeights(weights:number[]):number {
		let totalWeight = 0;

		for (let i = 0; i < weights.length; i++) {
			totalWeight += weights[i];
		}

		let ran = Tools.ranInt(1,totalWeight);

		for (let i = 0; i < weights.length; i++) {
			const weight = weights[i];

			if (ran <= weight) {
				return i;
			}
			else{
				ran -= weight;
			}
		}
	}

	public static randomWeightsByNum(weights:number[],num:number):number[] {
		const list:number[] = [];

		if (weights.length <= num) {
			for (let i = 0; i < weights.length; i++) {
				list.push(i);
			}

			return list;
		}
		
		for (let i = 0; i < num; i++) {
			const index = this.randomWeights(weights);

			list.push(index);
			weights.splice(index,1);
		}

		return list;
	}


	public static randomIndexsByNum(len:number,num:number):number[] {
		const totalIndex = [];

		for (let i = 0; i < len; i++) {
			totalIndex[i] = i;
		}

		const indexs = [];

		for (let i = 0; i < num; i++) {
			if (totalIndex.length == 0) {
				break;
			}

			const ran = Tools.ranInt(0,totalIndex.length-1);
			const index = totalIndex[ran];

			indexs.push(index);
			totalIndex.splice(ran,1);
		}

		return indexs;
	}

	// 只提取汉字
	GetChinese(strValue):string{ // eslint-disable-line
		if (strValue !== null && strValue !== '') {
			const reg = /[\u4e00-\u9fa5]/g;

			return strValue.match(reg).join('');
		}

		return '';
	}

	
	// /**
	//  * 取出中括号内的内容
	//  * @param text
	//  * @returns {string}
	//  */
	// export function getBracketStr(text) {
	// 	let result = ''
	// 	if (isObjEmpty(text))
	// 		return result
	// 	let regex = /\[(.+?)\]/g;
	// 	let options = text.match(regex)
	// 	if (!isObjEmpty(options)) {
	// 		let option = options[0]
	// 		if (!isObjEmpty(option)) {
	// 			result = option.substring(1, option.length - 1)
	// 		}
	// 	}
	// 	return result
	// }
	
	// /**
	//  * 取出小括号内的内容
	//  * @param text
	//  * @returns {string}
	//  */
	// export function getParenthesesStr(text) {
	// 	let result = ''
	// 	if (isObjEmpty(text))
	// 		return result
	// 	let regex = /\((.+?)\)/g;
	// 	let options = text.match(regex)
	// 	if (!isObjEmpty(options)) {
	// 		let option = options[0]
	// 		if (!isObjEmpty(option)) {
	// 			result = option.substring(1, option.length - 1)
	// 		}
	// 	}
	// 	return result
	// }
}
